package com.mtx.weatherreport;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mtx.weatherreport.Constant.SomeConstant;
import com.mtx.weatherreport.bean.NetUtil;
import com.mtx.weatherreport.bean.TodayWeather;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.title_city_img)
    ImageView mTitleCityImg;
    @BindView(R.id.title_city_dis)
    View mTitleCityDis;
    @BindView(R.id.title_city_name)
    TextView mTitleCityName;
    @BindView(R.id.title_update_img)
    ImageView mTitleUpdateImg;
    @BindView(R.id.title_city_share_img)
    ImageView mTitleCityShareImg;
    @BindView(R.id.title_base_img)
    ImageView mTitleBaseImg;
    @BindView(R.id.top_tool)
    RelativeLayout mTopTool;
    @BindView(R.id.city_name)
    TextView mCityName;
    @BindView(R.id.time)
    TextView mTime;
    @BindView(R.id.wet)
    TextView mWet;
    @BindView(R.id.c)
    TextView mTemperature;
    @BindView(R.id.pm_pic)
    ImageView mPmPic;
    @BindView(R.id.pm)
    TextView mPm;
    @BindView(R.id.pm_2)
    TextView mPm2;
    @BindView(R.id.wuran)
    TextView mWuran;
    @BindView(R.id.pm_block)
    RelativeLayout mPmBlock;
    @BindView(R.id.week)
    TextView mWeek;
    @BindView(R.id.sun_pic)
    ImageView mSunPic;
    @BindView(R.id.sun_rain)
    TextView mSunRain;
    @BindView(R.id.wind)
    TextView mWind;
    @BindView(R.id.weather_today_block)
    RelativeLayout mWeatherTodayBlock;
    @BindView(R.id.city_block)
    RelativeLayout mCityBlock;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    updateTodayWeather((TodayWeather)msg.obj);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        initView();
    }

    private void initView() {
        SharedPreferences sharedPreferences = getSharedPreferences("weather_info", MODE_PRIVATE);
        String cityCode = sharedPreferences.getString("number", "101010100");
        if (NetUtil.getNetworkState(this) != SomeConstant.NETWORK_NONE) {
            getNetworkWeatherInfo(cityCode);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        SharedPreferences sharedPreferences = getSharedPreferences("weather_info", MODE_PRIVATE);
        String cityCode = sharedPreferences.getString("number", "101010100");
        if (NetUtil.getNetworkState(this) != SomeConstant.NETWORK_NONE) {
            getNetworkWeatherInfo(cityCode);
        } else {
            Toast.makeText(this, getString(R.string.network_no_connect), Toast.LENGTH_SHORT).show();
        }
    }

    //===================================================================
    // 点击事件
    //===================================================================
    /**
     * 点击更新按钮
     */
    @OnClick(R.id.title_update_img)
    public void onClickUpdate() {
        SharedPreferences sharedPreferences = getSharedPreferences("weather_info", MODE_PRIVATE);
        String cityCode = sharedPreferences.getString("number", "101010100");
        if (NetUtil.getNetworkState(this) != SomeConstant.NETWORK_NONE) {
            getNetworkWeatherInfo(cityCode);
        } else {
            Toast.makeText(this, getString(R.string.network_no_connect), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 点击选择城市按钮
     */
    @OnClick(R.id.title_city_img)
    public void onClickSelectCity() {
        Intent intent = new Intent(this, SelectCityActivity.class);
        startActivityForResult(intent,0);
    }

    /**
     * 更新UI控件
     * @param obj
     */
    private void updateTodayWeather(TodayWeather obj) {
        mTitleCityName.setText(obj.getmCityName()+"天气");
        mCityName.setText(obj.getmCity());
        mTime.setText(obj.getmTime()+"发布");
        mWet.setText("湿度："+obj.getmWet());
        mPm.setText(obj.getmPm());
        mWuran.setText(obj.getmPmquality());
        mWeek.setText(obj.getmWeek());
        mTemperature.setText(obj.getmHigh()+"~"+obj.getmLow());
        mSunRain.setText(obj.getmClimate());
        mWind.setText("风力："+obj.getmWind());
        //空气质量情况
        int pmQuality;
        if(obj.getmPm()==null)   //如果pm为空
            pmQuality=0;
        else
            pmQuality= Integer.parseInt(obj.getmPm());
        if(pmQuality>=0&&pmQuality<=50){
            mPmPic.setImageResource(R.drawable.biz_plugin_weather_0_50);
        }else if(pmQuality>50&&pmQuality<=100){
            mPmPic.setImageResource(R.drawable.biz_plugin_weather_51_100);
        }else if(pmQuality>100&&pmQuality<=150){
            mPmPic.setImageResource(R.drawable.biz_plugin_weather_101_150);
        }else if(pmQuality>150&&pmQuality<=200){
            mPmPic.setImageResource(R.drawable.biz_plugin_weather_151_200);
        }else if(pmQuality>200&&pmQuality<=300){
            mPmPic.setImageResource(R.drawable.biz_plugin_weather_201_300);
        }else if(pmQuality>300){
            mPmPic.setImageResource(R.drawable.biz_plugin_weather_greater_300);
        }

        //天气状况图标
        String weather_img;
        if(obj.getmClimate()!=null) {
            weather_img = obj.getmClimate();
        }
        else
        {
            weather_img="no data";
        }
        int weather_image_id=obj.getImageWeather(weather_img);
        mSunPic.setImageResource(weather_image_id);
    }

    /**
     * 获取网络天气数据
     *
     * @param cityCode 城市码
     */
    private void getNetworkWeatherInfo(String cityCode) {
        final String netAddress = SomeConstant.NETWORK_WEATHER_ADDRESS + cityCode;

        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection con = null;
                TodayWeather todayWeather = null;

                try {
                    URL url = new URL(netAddress);  // 建立一个URL对象
                    con = (HttpURLConnection) url.openConnection();  // 打开一个链接
                    con.setRequestMethod("GET");  // 使用get请求
                    con.setConnectTimeout(8000);
                    con.setReadTimeout(8000);

                    InputStream in = con.getInputStream();  // 获取输入流，此时才有真正的建立连接
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder resultData = new StringBuilder();
                    String str;
                    while ((str = reader.readLine()) != null) {
                        resultData.append(str);  // 读取的文档内容
                    }
                    String resuleData_str = resultData.toString();

                    todayWeather = parseXML(resuleData_str);
                    if(todayWeather != null) {

                        Message msg = new Message();
                        msg.what = 1;
                        msg.obj =  todayWeather;
                        mHandler.sendMessage(msg);
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    if(con != null) {
                        con.disconnect();
                    }
                }
            }
        }).start();
    }

    /**
     * 解析xml
     *
     * @param resultData_str
     */
    private TodayWeather parseXML(String resultData_str) {
        TodayWeather todayweather = null;
        int fengli_count = 0;
        int week_count = 0;
        int high_count = 0;
        int low_count = 0;

        try {

            //通过XMLPullParseFactory获取XmlPullParse
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser xmlPullParser = factory.newPullParser();
            xmlPullParser.setInput(new StringReader(resultData_str));  //为Pull解析器设置输入流和编码风格

            int eventType = xmlPullParser.getEventType();
            Log.d("myweather", "parseXML");
            while (eventType != xmlPullParser.END_DOCUMENT) {
                switch (eventType) {
                    case XmlPullParser.START_DOCUMENT:
                        break;  //文档开始

                    case XmlPullParser.START_TAG:  //标签元素开始
                        if (xmlPullParser.getName().equals("resp")) {
                            todayweather = new TodayWeather();
                        }
                        if (todayweather != null) {
                            if (xmlPullParser.getName().equals("city")) {
                                eventType = xmlPullParser.next();
                                todayweather.setmCity(xmlPullParser.getText());
                                todayweather.setmCityName(xmlPullParser.getText());
                            } else if (xmlPullParser.getName().equals("updatetime")) {
                                eventType = xmlPullParser.next();
                                todayweather.setmTime(xmlPullParser.getText());
                            } else if (xmlPullParser.getName().equals("shidu")) {
                                eventType = xmlPullParser.next();
                                todayweather.setmWet(xmlPullParser.getText());
                            } else if (xmlPullParser.getName().equals("pm25")) {
                                eventType = xmlPullParser.next();
                                todayweather.setmPm(xmlPullParser.getText());
                            } else if (xmlPullParser.getName().equals("quality")) {
                                eventType = xmlPullParser.next();
                                todayweather.setmPmquality(xmlPullParser.getText());
                            } else if (xmlPullParser.getName().equals("date") && week_count == 0) {
                                eventType = xmlPullParser.next();
                                todayweather.setmWeek(xmlPullParser.getText());
                                week_count++;
                            } else if (xmlPullParser.getName().equals("high") && high_count == 0) {
                                eventType = xmlPullParser.next();
                                todayweather.setmHigh(xmlPullParser.getText().substring(2).trim()); //去掉首位空格第二个字符
                                high_count++;
                            } else if (xmlPullParser.getName().equals("low") && low_count == 0) {
                                eventType = xmlPullParser.next();
                                todayweather.setmLow(xmlPullParser.getText().substring(2).trim());
                                low_count++;
                            } else if (xmlPullParser.getName().equals("type")) {
                                eventType = xmlPullParser.next();
                                todayweather.setmClimate(xmlPullParser.getText());
                            } else if (xmlPullParser.getName().equals("fengli") && fengli_count == 0) {
                                eventType = xmlPullParser.next();
                                todayweather.setmWind(xmlPullParser.getText());
                                fengli_count++;
                            }
                        }
                        break;

                    case XmlPullParser.END_TAG:  //标签元素结束事件
                        break;

                }
                eventType = xmlPullParser.next();   //下一个标签元素并触发事件
            }


        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return todayweather;

    }
}
